/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.war.helpers;

import com.war.config.HtmlConfig;
import com.war.session.UserSession;
import java.util.ArrayList;
import java.util.HashMap;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;


/**
 *
 * @author Ambroise
 * @TODO Classe basée sur une version PHP incomplète. Fonctionne mais on peut virer du code inutile.
 *			L'attribut displayed n'est pas utilisé.
 *			Les méthodes removeMessageXXX ne sont pas utilisées.
 *			Le comportement actuel est la suppression pure et simple des messages une fois ceux-ci affichés.
 *			La classe peut être instanciée ou bien utilisée via les EL, pas de soucis particulier. (Non testé via instance)
 */
@ManagedBean(name="helperMessageHtml")
@RequestScoped
public class HelperMessageHtml{
	
	/**
	 * Get the EL context. See https://cwiki.apache.org/MYFACES/accessing-one-managed-bean-from-another.html
	 */
	private ELContext elContext = FacesContext.getCurrentInstance().getELContext();
	
	/**
	 * Import the UserSession.
	 */
	private UserSession session = (UserSession) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "userSession");
	
	/**
	 * Add a message to display in the browser.
	 * 
	 * @param message - The message content. Accept HTML tags.
	 * @param type - The type of message. [error, info, success, block]
	 * @param displayed - If the message is already displayed. [NB: Not use now.]
	 */
	public void addMessage(String message, String type, boolean displayed){
		ArrayList<HashMap<String, Object>> messages = session.getMessages();
		
		HashMap<String, Object> messageToAdd = new HashMap<String, Object>();
		messageToAdd.put("id", messages.size());
		messageToAdd.put("message", message);
		messageToAdd.put("type", type);
		messageToAdd.put("displayed", displayed);
		
		messages.add(messageToAdd);
		
		session.setMessages(messages);
	}
	
	/**
	 * Remove the message by ID.
	 * @param id 
	 */
	public void removeMessageById(Integer id){
		ArrayList<HashMap<String, Object>> messages = session.getMessages();
		
		messages.remove((int)id);
		
		session.setMessages(messages);
	}
	/**
	 * Remove messages by IDs. 
	 * @param ids - ArrayList of all id to delete.
	 * @TODO Don't works. the remove line don't works...
	 */
	public void removeMessageByArray(ArrayList<Integer> ids){
		ArrayList<HashMap<String, Object>> messages = session.getMessages();
		int nbErrors = messages.size();
		
		for (int i = 0; i < nbErrors; i++) {
			// Check if the element to delete exists.
			if(messages.contains(messages.get(i))){
				messages.remove((int)ids.get(i));
			}
		}
		
		// Update session.
		session.setMessages(messages);
	}
	
	/**
	 * Clear all messages in UserSession.messages
	 */
	public void clearMessages(){		
		session.setMessages(new ArrayList<HashMap<String, Object>>());
	}
	
	/**
	 * Display all message who are not displayed. Return HTML content.
	 * @return HTML
	 */
	public String displayErrorsHtml(){
		ArrayList<HashMap<String, Object>> messages = session.getMessages();
		
		HashMap<String, String> alert = new HtmlConfig().getAlert();
		
		String html = "";
		int nbErrors = messages.size();
		String lastType = "";
		
		// Ids to delete after the method is displayed.
		ArrayList<Integer> ids = new ArrayList<Integer>();
		
		for (int i = 0; i < nbErrors; i++) {
			// Current message.
			HashMap<String, Object> currentMessage = messages.get(i);
			Integer idMessage = (Integer)currentMessage.get("id");
			String message = (String)currentMessage.get("message");
			String type = (String)currentMessage.get("type");
			
			// Define the name to display.
			String typeName = "Erreur";
			
			// Define the class to use.
			String typeClass = alert.get("error");
			
			if(type.equals("error")){
					typeName = "Erreur";
					typeClass = alert.get("error");
					
			}else if(type.equals("block")){
				typeName = "Avertissement";
				typeClass = alert.get("block");
				
			}else if(type.equals("info")){
				typeName = "Information";
				typeClass = alert.get("info");
					
			}else if(type.equals("success")){
				typeName = "Opération réussie";
				typeClass = alert.get("success");
			}

			
			// Store the current id for delete after.
			ids.add(idMessage);
			
			String idHtml = "error-"+i;
			if(!lastType.equals((String)currentMessage.get("type"))){
				html += "<div id='"+idHtml+"' class='"+alert.get(type)+"'><a class='close' onclick='document.getElementById(\""+idHtml+"\").style.display = \"none\";'>×</a>";
			}
			
			// Redeclare header if the last type is different of the current type only.
			if(!lastType.equals(type)){
				html += "<h4 class='alert-heading'>"+typeName+" :</h4><br />";
			}

			// Add the current message.
			html += "<p>"+message+"</p>";

			// Enf of div if the next type is different to the current type.
			if(i+1 < nbErrors){
				if(messages.get(i+1).get("type") != type){
					html += "</div>";
				}
			}
			
			
			lastType = type;
		}
		
		html += "</div>";
		
		clearMessages();
		
		return html;
	}
	
	/**
	 * Return the number of errors who are not displayed.
	 * @return int - The number of errors.
	 */
	public int getNbErrors(){
		return session.getMessages().size();
	}
	
}
